import useToast from '@/hooks/useToast';
import Tools from '@/utils/tools';
import { navigate } from '@/utils/navigate';
import HomeRequest from '@/request/homeRequest';
import to from '@/utils/to';
import { useAppStore, useControllerStore } from '@/store';
import useModal from '@/hooks/useModal';
import eventBus from '@/utils/eventBus';

interface IEventCollection {
  onPress: (data: IServerBtnListBtnList | IBtnFormatsList, moduleType?: number, btnList?: IServerBtnListBtnList[], searchText?: string) => void;
  onLongPress: (data: IServerBtnListBtnList | IBtnFormatsList) => void;
}

const { showToast } = useToast();
const { showModal } = useModal();
const store = useAppStore();
const { beeperId } = store.$state;

/**
 * 处理产品相关的界面判断
 * @param data
 */
async function handleProductSwitch(data: IServerBtnListBtnList | IBtnFormatsList) {
  const { eventId } = data;
  // 10: 进入选购界面 18: 挂号对接 19: 影像预约对接
  if ([10, 18, 19].some((item) => item === eventId)) {
    // 产品选购界面
    navigate({ url: `/subcontract/home/merchantProduct/index` });
  } else {
    const [err, res] = await to(HomeRequest.GetBtnDefaultGoods({ beeperId, btnId: data.id, hasLoading: true }));
    if (err) return;
    const { goodsType } = res.data.goods;
    const { harvestAddressId } = res.data?.addressInfo;
    if (!harvestAddressId) {
      await showToast('该产品没有地址信息');
      return;
    }

    switch (eventId) {
      case 11:
      case 12:
        // 如果不是补差价产品
        if (goodsType && goodsType !== 15) {
          // 快捷下单
          navigate({ url: `/subcontract/home/freePayOrderPlc/index?data=${encodeURIComponent(JSON.stringify(res.data))}` });
        } else {
          //弹窗支付下单 - 补差价产品
          useControllerStore().$patch({ compPriceDiffPopupData: { data: res.data, eventId: data.eventId, linkUrl: data.linkUrl } });
        }
        break;
      case 13:
        // 详情页下单
        navigate({ url: `/subcontract/home/productDetail/index?product=${encodeURIComponent(JSON.stringify(res.data.goods))}&hasHomePath=true&hasSku=${goodsType === 2 || res.data.goods.variantState === 2 ? 'true' : 'false'}` });
        break;
      case 14:
        // 结算页下单
        navigate({ url: `/subcontract/home/submitOrder/index?products=${encodeURIComponent(JSON.stringify({ ...res.data.goods, nums: 1 }))}` });
        break;
    }
  }
}

/**
 * 按钮、模版事件类型为点击事件
 * @param data
 * @param moduleType
 * @param btnList
 */
async function handleClickOnEvent(data: IServerBtnListBtnList | IBtnFormatsList, moduleType?: number, btnList?: IServerBtnListBtnList[]) {
  const { eventId, linkUrl } = data;
  switch (eventId) {
    // 连接wifi
    case 1:
      await showToast('功能开发中');
      break;
    // 拨打电话
    case 2:
      await Tools.callPhone(linkUrl);
      break;
    // 合并按键
    case 6:
      if (btnList) useControllerStore().$patch({ mergerCaseModalData: btnList.filter((item) => Number(item.parentBtnCode) === data.btnCode) });
      break;
    // 一键出院
    case 51:
      showModal('确认出院吗？', {
        success: async (res) => {
          if (res.confirm) {
            const [err] = await to(HomeRequest.OneClickDischarge({ beeperId: store.$state.beeperId, btnId: store.$state.btnInformation, hasLoading: true }));
            if (err) return;
            showToast('出院成功');
          }
        },
      });
      break;
  }
}

/**
 * 按钮、模版事件为跳转内部界面
 * @param data
 * @param moduleType
 */
async function handleJumpToInternalScreen(data: IServerBtnListBtnList | IBtnFormatsList, moduleType?: number) {
  const { eventId } = data;
  switch (eventId) {
    // 分类资讯界面
    case 3:
      navigate({ url: '/subcontract/home/newsClassification/index' });
      break;
    // 聊天
    case 4:
      await showToast('功能开发中');
      break;
    // 活动报名
    case 5:
      navigate({ url: '/subcontract/home/activityRegistration/index' });
      break;
    // 物业通知
    case 7:
      //这里的linkUrl是栋Id
      navigate({ url: '/subcontract/home/sendNotify/index?linkUrl=' + data.linkUrl + '&btnId=' + data.id });
      break;
    // 健康打卡
    case 53:
      navigate({ url: '/subcontract/home/healthCheckIn/index' });
      break;
    // 固定资讯
    case 54:
      navigate({ url: `/subcontract/home/newsClassification/NewsDetails?id=${data.linkUrl}` });
      break;
    // 设备详情
    case 55:
      const [err, res] = await to(HomeRequest.ObtainDeviceListUnderDeviceCategory({ beeperId: store.$state.beeperId, btnId: data.id, hasLoading: true }));
      if (err) return;
      if (res.data.length === 0) {
        showToast('没有符合的绑定设备');
        return;
      }
      useControllerStore().$patch({ deviceListPopupData: res.data });
      break;
    // 通知详情
    case 57:
      navigate({ url: '/subcontract/home/notifyDetail/index' });
      break;
    // 受困上报
    case 58:
      navigate({ url: '/subcontract/home/trappedReport/index' });
      break;
    // 火情上报
    case 59:
      navigate({ url: '/subcontract/home/fireReport/index' });
      console.log('火情上报');
      break;
    // 物业缴费
    case 60:
      navigate({ url: '/subcontract/home/propertyPayment/index' });
      break;
    // 消防报警
    case 61:
      navigate({ url: '/subcontract/home/fireDetection/index' });
      break;
  }
}

const EventCollection: IEventCollection = {
  // 触摸事件
  onPress: async (data, moduleType, btnList, searchText) => {
    // 搜索跳转
    if (moduleType && moduleType === 6) {
      navigate({ url: `/subcontract/home/productSearch/index?data=${JSON.stringify(data)}&searchText=${searchText}` });
      return;
    }
    const { relationType, linkUrl } = data;
    switch (relationType) {
      // 产品
      case 1:
        await handleProductSwitch(data);
        break;
      //  web链接
      case 2:
        navigate({ url: `/subcontract/person/webView/index?url=${linkUrl}` });
        break;
      // 小程序链接
      case 3:
        const _linkUrl = linkUrl.split(',');
        let params: UniNamespace.NavigateToMiniProgramOptions = { path: '', appId: '' };
        if (_linkUrl.length > 1) {
          params = { path: _linkUrl[1], appId: _linkUrl[0] };
        } else {
          params = { shortLink: linkUrl, appId: '' };
        }
        await uni.navigateToMiniProgram({ ...params });
        break;
      // 点击事件
      case 4:
        await handleClickOnEvent(data, moduleType, btnList);
        break;
      // 内部界面
      case 5:
        await handleJumpToInternalScreen(data, moduleType);
        break;
    }
  },

  // 长按唤醒语音下单
  onLongPress(data) {
    const { relationType, eventId, voiceOrderFlag } = data;
    if (relationType === 1 && (eventId === 10 || eventId === 18 || eventId === 19) && voiceOrderFlag) {
      uni.authorize({
        scope: 'scope.record',
        success: () => {
          eventBus.emit('callRecordingModal', { visible: true, key: 'voiceOrdering' });
        },
        fail: () => {
          showModal(
            '需要获取您的录音权限，请前往设置中授权',
            {
              success: (res) => {
                if (res.confirm) uni.openSetting();
              },
            },
            '请求录音权限',
          );
        },
      });
    }
  },
};

export default EventCollection;
